package com.campus.controller;

import com.campus.common.CampusWall;
import com.campus.common.Result;
import com.campus.entity.FileUploads;
import com.campus.entity.Users;
import com.campus.mapper.FileUploadsMapper;
import com.campus.utils.MD5Util;
import com.campus.utils.SnowFlakeUtil;
import com.campus.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/api")
public class FileController {
    //文件上传路径
    @Value("${file.upload-path}")
    private String filePath;
    @Autowired
    private TokenUtils tokenUtils;
    @Autowired
    private FileUploadsMapper fileUploadsMapper;
    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping("/file/upload")
    public Result uploadFile(MultipartFile file, HttpServletRequest request) {

        //获取图片的原始名字
        String originalFilename = file.getOriginalFilename();
        long fileSize= file.getSize();
        //将图片的名字做更改防止图片名字重复
        String newFileName = UUID.randomUUID()+originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(newFileName);
        File file1 = new File(filePath);
        if (!file1.exists()){
            file1.mkdirs();
        }
        //这里要把图片名字上传到数据库
        String token = request.getHeader(CampusWall.CAMPUS_TOKEN);

        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 移除 "Bearer " 前缀
            System.out.println("处理后的token: " + token);
        } else {
            System.out.println("Token格式不正确或为空: " + token);
            throw new RuntimeException("Token格式不正确，请登录！");
        }
        Users user = tokenUtils.getCurrentUser(token);
        FileUploads fileUpload = new FileUploads(SnowFlakeUtil.getId().toString(), user.getUserId(), originalFilename, newFileName,
                filePath, "/file/upload", fileSize, originalFilename.substring(originalFilename.lastIndexOf(".") + 1),
                file.getContentType(), MD5Util.hmacSign(newFileName), "POST", null, 1, null);
        int i = fileUploadsMapper.insertFile(fileUpload);
        if (i>=1){
            try {
                //写图片
                file.transferTo(new File(filePath,newFileName));


            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return Result.ok("上传成功",fileUpload);
        }
        return Result.err(Result.CODE_500,"文件上传失败");


    }
}
